import { enable as enableDarkMode, disable as disableDarkMode } from 'darkreader'

const storage = window.localStorage
const storageKey = 'darkThemeOption'
const darkThemeOption = {
  brightness: 100,
  contrast: 90,
  sepia: 0
}

function isObj (data) {
  return data && typeof data === 'object' && !Array.isArray(data)
}

export default {
  init () {
    let opt = storage.getItem(storageKey)
    try {
      opt = JSON.parse(opt)
    } catch (e) {
      opt = null
    }
    if (isObj(opt)) {
      opt = Object.assign({}, darkThemeOption, opt)
    }
    storage.setItem(storageKey, JSON.stringify(opt))
    enableDarkMode(opt)
  },
  update (opt) {
    if (!isObj(opt)) opt = {}
    opt = Object.assign({}, darkThemeOption, opt)
    storage.setItem(storageKey, JSON.stringify(opt))
    enableDarkMode(opt)
  },
  enable () {
    enableDarkMode(darkThemeOption)
  },
  disable () {
    disableDarkMode()
  }
}
